<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JNI,NDK,Java,Linxu,C++," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Android 进阶系列的第一篇。 JNI 基础知识了解，Hello JNI 编写。 JNI 是Java 提供的和本地通信的一种方式 java native interface,之前一直不明白JNI和NDK的区别。NDK 是native develop kit ，android 提供的一套合本地通信的方式，NDK的基础是JNI，这篇主要记录如何从零开始学习JNI，把NDK的学习放在后面，主要是觉">
<meta name="keywords" content="JNI,NDK,Java,Linxu,C++">
<meta property="og:type" content="article">
<meta property="og:title" content="JNI step by step 0">
<meta property="og:url" content="http://imesong.com/2016/04/19/2016/JNI-step-by-step-0/index.html">
<meta property="og:site_name" content="imesong">
<meta property="og:description" content="Android 进阶系列的第一篇。 JNI 基础知识了解，Hello JNI 编写。 JNI 是Java 提供的和本地通信的一种方式 java native interface,之前一直不明白JNI和NDK的区别。NDK 是native develop kit ，android 提供的一套合本地通信的方式，NDK的基础是JNI，这篇主要记录如何从零开始学习JNI，把NDK的学习放在后面，主要是觉">
<meta property="og:updated_time" content="2017-04-19T04:36:25.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JNI step by step 0">
<meta name="twitter:description" content="Android 进阶系列的第一篇。 JNI 基础知识了解，Hello JNI 编写。 JNI 是Java 提供的和本地通信的一种方式 java native interface,之前一直不明白JNI和NDK的区别。NDK 是native develop kit ，android 提供的一套合本地通信的方式，NDK的基础是JNI，这篇主要记录如何从零开始学习JNI，把NDK的学习放在后面，主要是觉">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://imesong.com/2016/04/19/2016/JNI-step-by-step-0/"/>





  <title> JNI step by step 0 | imesong </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb36183ed65a7652b909d352ab2166";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">imesong</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Change the world by coding!</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://imesong.com/2016/04/19/2016/JNI-step-by-step-0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="imesong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://7xrkqt.com1.z0.glb.clouddn.com/avatar.jpg-avatar">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="imesong">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JNI step by step 0
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-04-19T21:12:43+08:00">
                2016-04-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JNI/" itemprop="url" rel="index">
                    <span itemprop="name">JNI</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <blockquote>
<p><strong>Android 进阶系列的第一篇</strong>。 JNI 基础知识了解，Hello JNI 编写。</p>
<p>JNI 是Java 提供的和本地通信的一种方式 java native interface,之前一直不明白JNI和NDK的区别。NDK 是native develop kit ，android 提供的一套合本地通信的方式，NDK的基础是JNI，这篇主要记录如何从零开始学习JNI，把NDK的学习放在后面，主要是觉得NDK对于比较小的项目可以使用，复杂的项目，都是在Linux下开发好native 代码，再集成到应用层中，不会在 Android Studio 或者 Eclipse 中直接编译。</p>
<p>本文主要参考 <a href="http://www.cnblogs.com/icejoywoo/archive/2012/02/22/2363709.html" target="_blank" rel="external">使用JNI进行Java与C/C++语言混合编程(1)–在Java中调用C/C++本地库</a> ,原文作者使用Windows 环境，我这里使用的 <strong>Ubuntu 12.04</strong> ，这两者还是有很大区别的。</p>
</blockquote>
<a id="more"></a>
<h3 id="JNI的主要思路"><a href="#JNI的主要思路" class="headerlink" title="JNI的主要思路"></a>JNI的主要思路</h3><ul>
<li>编写java代码</li>
<li>使用 javah 生成头文件</li>
<li>根据头文件，编写 cpp 文件</li>
<li>编译 so 文件</li>
<li>加载 so ,调试功能<br>在这五步中，真是一步一坑，走的是异常艰难。<br>Sample.java 按照原文链接中的代码编写，没什么问题。</li>
</ul>
<h3 id="编写-Java-代码"><a href="#编写-Java-代码" class="headerlink" title="编写 Java 代码"></a>编写 Java 代码</h3><p>编写 JNI 的 HelloWorld 难度不大的，就只有一个 Native 方法。 </p>
<h3 id="使用-javah-生成头文件"><a href="#使用-javah-生成头文件" class="headerlink" title="使用 javah 生成头文件"></a>使用 javah 生成头文件</h3><p>生成头文件，看起来很简单</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">javah Sample</div></pre></td></tr></table></figure>
<p>如果你认为就这么简单，那就too young~.<br>第一个错误来了 </p>
<blockquote>
<p>javah 找不到类文件</p>
</blockquote>
<p>这里主要是对javah 这里命令不了解</p>
<h3 id="编写-cpp-文件"><a href="#编写-cpp-文件" class="headerlink" title="编写 cpp 文件"></a>编写 cpp 文件</h3><p>编写 cpp 文件没什么问题，照着写就可以了。</p>
<h3 id="编译-so"><a href="#编译-so" class="headerlink" title="编译 so"></a>编译 so</h3><p>编译的时候，最开始调用的命令</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">g++ Sample.cpp</div></pre></td></tr></table></figure>
<p>果然是不可以的。</p>
<blockquote>
<p>In file include from Sample.cpp:1:0:<br>fatal error jni.h:No such file or directory #include<jni.h></jni.h></p>
</blockquote>
<p>搜索之后，是因为找不到 jni.h 文件</p>
<p>命令调整位</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">g++ -shared -fpic -I/home/you_usr/JDK_PATH/include -I/home/your_usr/JDK_PATH/include/linux Sample.cpp -o Sample.so</div></pre></td></tr></table></figure>
<p>不要以为这样就完事大吉了<br>错误信息如下</p>
<blockquote>
<p>Sample.cpp in function _jstring<em> java_sample_stringMethod(JNIEnv</em>,jobject,jstring);<br>Sample.cpp error:strupr was not declared in this scope return env-&gt;NewStringUTF(strupr(cap));</p>
</blockquote>
<p>对于我这个cpp 菜鸟，对这个问题一阵好搜啊，请教同事才知，是因为 c++ 标准库中没有strupr 这个函数，在 VS C++中有这个东西，所以Windows 平台下是有多，Linux 下没有多。解决版本就是先把这个函数去掉然后再编译。</p>
<p>这下还有另外一个问题</p>
<blockquote>
<p>in function <em>start undefined reference to main</em></p>
</blockquote>
<p>没有 main 方法。添加一个，再编译。<br>这下编译出 Sample.so </p>
<h3 id="加载-so-调试功能"><a href="#加载-so-调试功能" class="headerlink" title="加载 so 调试功能"></a>加载 so 调试功能</h3><p>加载 so ,编译 Sample.class</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">java Sample</div></pre></td></tr></table></figure>
<p>问题又来了 </p>
<blockquote>
<p>UnsatisfiedLinkError cann’t dynamically load executable<br>no so in java.library.path</p>
</blockquote>
<p>搜索之后，是因为无法找到so,java.library.path。加载 so 有两种方式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">System.load();</div><div class="line">System.loadLibrary();</div></pre></td></tr></table></figure>
<p>调试之后，使用第一种加载绝对路径下多so,第二种加载方式调整之后还是不能使用</p>
<p><a href="http://www.ibm.com/developerworks/java/tutorials/j-jni/j-jni-pdf.pdf" target="_blank" rel="external">IBM hello-jni 资料</a></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="http://7xrkqt.com1.z0.glb.clouddn.com/WechatCode.jpeg" alt="imesong wechat" style="width: 200px; max-width: 100%;"/>
    <div>添加关注</div>
</div>


      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JNI/" rel="tag"># JNI</a>
          
            <a href="/tags/NDK/" rel="tag"># NDK</a>
          
            <a href="/tags/Java/" rel="tag"># Java</a>
          
            <a href="/tags/Linxu/" rel="tag"># Linxu</a>
          
            <a href="/tags/C/" rel="tag"># C++</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/04/24/2016/NDK-step-by-step-1/" rel="next" title="NDK step by step 1">
                <i class="fa fa-chevron-left"></i> NDK step by step 1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/04/19/2016LearningList/" rel="prev" title="2016LearningList">
                2016LearningList <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://7xrkqt.com1.z0.glb.clouddn.com/avatar.jpg-avatar"
               alt="imesong" />
          <p class="site-author-name" itemprop="name">imesong</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/imesong" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/youyoubaren/home?wvr=5" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/imesong" target="_blank" title="Zhihu">
                  
                    <i class="fa fa-fw fa-zhihu"></i>
                  
                  Zhihu
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/25e16af753ad/latest_articles" target="_blank" title="Jianshu">
                  
                    <i class="fa fa-fw fa-jianshu"></i>
                  
                  Jianshu
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#JNI的主要思路"><span class="nav-number">1.</span> <span class="nav-text">JNI的主要思路</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写-Java-代码"><span class="nav-number">2.</span> <span class="nav-text">编写 Java 代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-javah-生成头文件"><span class="nav-number">3.</span> <span class="nav-text">使用 javah 生成头文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写-cpp-文件"><span class="nav-number">4.</span> <span class="nav-text">编写 cpp 文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编译-so"><span class="nav-number">5.</span> <span class="nav-text">编译 so</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#加载-so-调试功能"><span class="nav-number">6.</span> <span class="nav-text">加载 so 调试功能</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">imesong</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  

  

  

  

</body>
</html>
